#!/bin/bash

# 设置日期格式为YYYYMMDD
DATE=$(date +"%Y%m%d")
SOURCE_IMAGE="registry.cn-beijing.aliyuncs.com/dolphi/heygem_dolphi:0.1"
TARGET_IMAGE="registry.cn-beijing.aliyuncs.com/dolphi/heygem_dolphi:${DATE}"

# 显示脚本说明
echo "====================================================="
echo "阿里云Docker镜像构建和推送脚本"
echo "====================================================="
echo "源镜像: ${SOURCE_IMAGE}"
echo "目标镜像: ${TARGET_IMAGE}"
echo "====================================================="

# 登录阿里云容器镜像服务
echo "正在登录阿里云容器镜像服务..."
docker login --username=179049114@qq.com registry.cn-beijing.aliyuncs.com

# 检查登录是否成功
if [ $? -ne 0 ]; then
    echo "登录失败，请检查凭据后重试"
    exit 1
fi

# 拉取源镜像
echo "正在拉取源镜像: ${SOURCE_IMAGE}..."
docker pull ${SOURCE_IMAGE}

# 查找正在运行的容器ID
CONTAINER_ID=$(docker ps --filter "ancestor=${SOURCE_IMAGE}" --format "{{.ID}}")

if [ -z "$CONTAINER_ID" ]; then
    echo "没有找到运行中的容器，使用源镜像直接打标签"
    # 为源镜像打新标签
    docker tag ${SOURCE_IMAGE} ${TARGET_IMAGE}
else
    echo "找到运行中的容器ID: ${CONTAINER_ID}"
    # 从运行中的容器创建新镜像
    echo "正在从容器创建新镜像..."
    docker commit ${CONTAINER_ID} ${TARGET_IMAGE}
fi

# 推送新镜像到阿里云
echo "正在推送镜像到阿里云: ${TARGET_IMAGE}..."
docker push ${TARGET_IMAGE}

# 检查推送结果
if [ $? -ne 0 ]; then
    echo "镜像推送失败"
    exit 1
else
    echo "====================================================="
    echo "镜像构建和推送成功!"
    echo "新镜像: ${TARGET_IMAGE}"
    echo "====================================================="
fi 